<template>
  <div>
    <t-tree-select @change="deptChange" v-if="formData.isInnerCompany==='1'"  clearable filterable
                   :treeProps="{keys: {value: 'label'}}" v-model="formData.company" :data="deptMenuOptions"
                   placeholder="选择单位">
      <template #label>
        <t-switch
          size="medium"
          v-model="formData.isInnerCompany"
          :label="['内部', '外部']"
          :customValue="['1', '0']"
          @change="()=>{formData.company='';formData.companyId=null}"
        ></t-switch>
      </template>
    </t-tree-select>
    <t-select
      v-else
      v-model="formData.company"
      creatable
      filterable
      placeholder="请输入"
      :loading="companyLoading"
      @search="remoteCompanyMethod"
      :options="companyOptions"
      @create="createCompanyOptions"
    >
      <template #label>
        <t-switch
          size="medium"
          v-model="formData.isInnerCompany"
          :label="['内部', '外部']"
          :customValue="['1', '0']"
          @change="()=>{formData.company='';formData.companyId=null}"
        ></t-switch>
      </template>
    </t-select>
  </div>
</template>

<script>
export default {
  name: "Inner-outer-company-select", // 内外部单位选择
  props: {
    formData:{
      type: Object,
      default: () => {
      }
    }
  },
  data(){
    return {
      deptMenuOptions: [],
      companyLoading: false,
      companyOptions: []
    }
  },
  created() {
    this.getDeptTreeSelect();
  },
  methods: {
    deptChange(val, content) {
      this.formData.companyId = content.data.id;
    },
    getDeptTreeSelect(id) {
      return this.$api.system.dept.treeSelectAllIn().then(response => {
        this.deptMenuOptions = response.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    remoteCompanyMethod(search) {
      this.companyLoading = true;
      this.$api.system.dept.selectAllOutDeptList({deptName: search}).then(response => {
        this.companyOptions = response.data.map(val => ({
          ...val,
          label: `${val.deptName}`,
          value: val.deptName,
        }));
        this.companyLoading = false;
      }).catch((e) => {
        this.companyLoading = false;
        this.$message.error(e.toString());
      });
    },
    createCompanyOptions(value) {
      this.companyOptions.push({
        label: `${value}`,
        value,
      });
    },
  }
}
</script>

<style scoped>

</style>
